import axios from 'axios'
import store from '@/store'
import router from '@/router'
import to from 'await-to-js'
import JsonBigint from 'json-bigint'

// 1. 创建一个新的axios实例
// 2. 使用json-bigint转换超出最大安全整数的ID
// 3. 请求拦截器：在请求头携带token
// 4. 响应拦截器：处理token失效
// 5. 导出一个axios的调用函数，返回值是promise，且一定有结果 [err,result]

export const baseURL = 'http://geek.itheima.net/'

const instance = axios.create({
  baseURL,
  timeout: 5000,
  // 处理最大安全整数
  transformResponse: [data => {
    if (data) {
      return JsonBigint.parse(data)
    }
  }]
})

// 请求拦截器
instance.interceptors.request.use(config => {
  const token = store.state.user.token
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
}, err => Promise.reject(err))

// 响应拦截器
instance.interceptors.response.use(res => res, err => {
  if (err.response && err.response.status === 401) {
    // token失效
    store.commit('user/setToken', null)
    router.push('/login?returnUrl=' + encodeURIComponent(router.currentRoute.fullPath))
  }
  return Promise.reject(err)
})

export default ({ url, method = 'get', params, data, headers }) => {
  const promise = instance({ url, method, params, data, headers })
  return to(promise)
}
